import Axios from "axios";
import Qs from "qs";
import Config from "@/_config/config.js";
// import Vuex from "@/plugins/vuex";
//如果传入的url 有http,就不会解析
//addHead默认是true（如果data里面有addHead=false系统就会不加头部header）
let http = {
  //配置关键字，匹配host
  reqUrl: Config.reqUrl,
  /**
   * get
   * @param url  接口地址
   * @param data 参数（json）
   * @param isDefer 是否延迟500ms
   * @param headers 自定义头部
   */
  Get(url, data, isDefer = false, headers = null) {
    let th = this;
    return new Promise(function(resolve, reject) {
      let json = {
        url: url,
        method: "get",
        params: th.FilterParams(data)
      };
      if (headers) {
        json["headers"] = headers;
      }
      Axios(json)
        .then(function(res) {
          if (res.status == 200) {
            th.OutLog(res, "success");
            if (isDefer) {
              setTimeout(() => {
                resolve(res.data);
              }, 500);
            } else resolve(res.data);
          } else {
            th.OutLog(res);
            reject(res);
          }
        })
        .catch(function(error) {
          th.OutLog(error);
          reject(error);
        });
    });
  },
  /**
   * post
   * @param url  接口地址
   * @param data 参数（json） params
   * @param isDefer 是否延迟500ms
   * @param headers 自定义头部
   */
  Post(url, data, isDefer = false, headers = null) {
    let th = this;
    //2021.04.28 何杰接口要quearystring和formdata  2种格式传参...  对象添加params属性，用于quearystring传参
    if (data.hasOwnProperty("params")) {
      url = url + "?" + data.params;
    }
    return new Promise(function(resolve, reject) {
      let json = {
        method: "post",
        url: url,
        data: Qs.stringify(data)
      };
      if (headers) {
        json["headers"] = headers;
      }
      Axios(json)
        .then(res => {
          if (res.status == 200) {
            th.OutLog(res, "success");
            if (isDefer) {
              setTimeout(() => {
                resolve(res.data);
              }, 500);
            } else resolve(res.data);
          } else {
            th.OutLog(res);
            reject(res);
          }
        })
        .catch(error => {
          th.OutLog(error);
          reject(error);
        });
    });
  },
  /**
   * post
   * @param url  接口地址
   * @param data 参数（json）
   * @param isDefer 是否延迟500ms
   * @param headers 自定义头部
   */
  PostJson(url, data, isDefer = false, headers = null) {
    let th = this;
    return new Promise(function(resolve, reject) {
      let json = {
        method: "post",
        url: url,
        data: JSON.stringify(data),
        headers: { "Content-Type": "application/json;charset=UTF-8" }
      };
      if (headers) {
        Object.assign(j.headers, headers);
      }
      Axios(json)
        .then(res => {
          if (res.status == 200) {
            th.OutLog(res, "success");
            if (isDefer) {
              setTimeout(() => {
                resolve(res.data);
              }, 500);
            } else resolve(res.data);
          } else {
            th.OutLog(res);
            reject(res);
          }
        })
        .catch(error => {
          th.OutLog(error);
          reject(error);
        });
    });
  },
  /**
   * 上传文件
   * @param url 接口地址
   * @param data 参数（json）
   * @param fn 上传时进度回调
   * @param headers 自定义头部
   */
  UpFile(url, data, fn, headers = null) {
    let th = this;
    let param = new FormData(); // 创建form对象
    for (let item in data) {
      param.append(item, data[item]);
    }
    return new Promise(function(resolve, reject) {
      let json = {
        method: "post",
        url: url,
        data: param,
        headers: { "Content-Type": "multipart/form-data" },
        onUploadProgress: function(progressEvent) {
          if (progressEvent.lengthComputable) {
            if (typeof fn == "function") {
              let s = (progressEvent.loaded / progressEvent.total) * 100;
              fn(s.toFixed(1));
            }
          }
        }
      };
      if (headers) Object.assign(json.headers, headers);
      Axios(json)
        .then(res => {
          if (res.status == 200) {
            th.OutLog(res, "success");
            resolve(res.data);
          } else {
            th.OutLog(res);
            reject(res);
          }
        })
        .catch(error => {
          th.OutLog(error);
          reject(error);
        });
    });
  },
  OutLog(obj, type = "error") {
    if (type == "error") {
    } else {
      // console.log("请求完成", obj);
    }
  },
  //解析地址
  AnalysisUrl(url) {
    let th = this;
    let resultUrl = "";
    if (url.includes("http")) {
      //保护http的请求不需要解析
      resultUrl = url;
    } else {
      for (let key in th.reqUrl) {
        let urlIndex = url.startsWith(key);
        if (urlIndex) {
          //找到前缀
          let newUrl = url.substring(key.length);
          resultUrl = th.reqUrl[key] + newUrl;
          break;
        }
      }
    }
    return resultUrl;
  },
  //过滤没有值的参数（Get）
  FilterParams(data) {
    let j = {};
    for (let p in data) {
      let value = data[p];
      if (value !== "" && value !== null) {
        j[p] = value;
      }
    }
    return j;
  }
};
// 添加请求拦截器
Axios.interceptors.request.use(
  function(config) {
    let newUrl = http.AnalysisUrl(config.url);
    config.url = newUrl;
    //判断是否加accessToken
    let addHead = true;
    if (config.method == "get") {
      if (config.params && config.params.addHead === false) {
        addHead = false;
      }
    } else if (config.method == "post") {
      let headIndex = config.data.indexOf("addHead=false");
      if (headIndex != -1) addHead = false;
    }
    if (addHead == true) {
      let token = window.$vue.adminUser.token;
      // sessionStorage.getItem("adminUser");
      if (token) {
        // let token = JSON.parse(adminUser).token;
        config.headers["accessToken"] = token;
        // if (process.env.NODE_ENV == "development") {
        //   config.headers["env"] = "test";
        // }
      }
    }
    return config;
  },
  function(error) {
    return Promise.reject(error);
  }
);
// 添加响应拦截器
Axios.interceptors.response.use(
  function(response) {
    let data = response.data;
    //两个felse代表未登录
    if (data.executed == false && data.success == false) {
      window.location.href = "/?nologin=true";
    }
    return response;
  },
  function(error) {
    if (error.response) {
      let data = error.response.data;
      //两个felse代表未登录
      if (data.executed == false && data.success == false) {
        window.location.href = "/?nologin=true";
      }
    }
    return Promise.reject(error);
  }
);
export default http;
